package org.ceteca.explica.client.gui;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TreeEditor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

public class EntityExtensionCatalogTextListener implements Listener {
	private Tree tree;
	private TreeItem item;
	private Composite composite;
	private Text text;
	private TreeEditor editor;
	private int inset;
	
	public EntityExtensionCatalogTextListener(Tree tree, TreeItem item, Composite composite, Text text, TreeEditor editor, int inset) {
		this.tree = tree;
		this.item = item;
		this.composite = composite;
		this.text = text;
		this.editor = editor;
		this.inset = inset;
	}
	
	public void handleEvent (final Event e) {
		switch (e.type) {
			case SWT.FocusOut:
				item.setText (1, text.getText ());
				composite.dispose ();
				break;
			case SWT.Verify:
				String newText = text.getText ();
				String leftText = newText.substring (0, e.start);
				String rightText = newText.substring (e.end, newText.length ());
				GC gc = new GC (text);
				Point size = gc.textExtent (leftText + e.text + rightText);
				gc.dispose ();
				size = text.computeSize (size.x, SWT.DEFAULT);
				editor.horizontalAlignment = SWT.LEFT;
				Rectangle itemRect = item.getBounds (), rect = tree.getClientArea ();
				editor.minimumWidth = Math.max (size.x, itemRect.width) + inset * 2;
				int left = itemRect.x, right = rect.x + rect.width;
				editor.minimumWidth = Math.min (editor.minimumWidth, right - left);
				editor.minimumHeight = size.y + inset * 2;
				editor.layout ();
				break;
			case SWT.Traverse:
				switch (e.detail) {
					case SWT.TRAVERSE_RETURN:
						item.setText (1, text.getText ());
						//FALL THROUGH
					case SWT.TRAVERSE_ESCAPE:
						composite.dispose ();
						e.doit = false;
				}
				break;
		}
	}
}
